<?php

namespace App\Http\Controllers\admin;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;

use DB;

class TypeController extends Controller
{
    //
    public function index(Request $request)
    {
    	//保存搜索条件
    	$where = [];
    	//实例化要操作的表
    	$db = DB::table('type')->select(DB::raw('*,concat(path,id) as pathid'))->orderBy('pathid');
    	//判断有没有搜索name字段的值
        // dd();
    	if($request->has('name')){
    		// 获取要搜索的name字段的值
    		$name = $request->input('name');
    		//添加where模糊匹配条件
    		$db->where('name','like',"%{$name}%");
    		$where['name'] = $name;
    	}
    	// 分页
    	$list = $db->paginate(8);
        // $list = $db->get();
    	//加载模板
    	return view('admin.type.index',['list'=>$list,'where'=>$where]);
    }

    public function create()
    {
    	return view('admin.type.add');
    }

    public function store(Request $request)
    {
    	//自动规则
    	$messages = [
    		'required' => ':attribute 的字段是必要的',
    	];
    	//
    	$this->validate($request, [
	        'name' => 'required|unique:type|max:16',
	    ],$messages);
    	$data = $request->except('_token');
    	$id = DB::table('type')->insertGetId($data);
    	if($id>0){
    		return redirect('/admin/type')->with('msg','添加成功');
    	}
    }

    public function destroy($id)
    {
        $ob = DB::table('type')->where('pid',$id)->get();
        if(count($ob)>0){
           return redirect('admin/type')->with('msg','要删除此类必须先删除此类下的子类');
        }

    	$row = DB::table('type')->where('id',$id)->delete();
    	if($row>0){
    		return redirect('admin/type')->with('msg','删除成功');
    	}
    }

    public function edit($id)
    {
    	$type = DB::table('type')->where('id',$id)->first();
    	return view('admin.type.edit',['type'=>$type]);
    }

    public function update($id,Request $request)
    {
    	$data = $request->only('name');
    	$row = DB::table('type')->where('id',$id)->update($data);
    	if($row>0){
    		return redirect('admin/type')->with('msg','修改成功');
    	}
    }

    public function createSon($id)
    {
        $list = DB::table('type')->where('id',$id)->first();
        return view('admin.type.addSon',['list'=>$list]);
    }

    public function storeSon(Request $request)
    {
        // dd($request->all());
        $data = $request->except('_token');
        $par = DB::table('type')->where('id',$request->input('pid'))->first();

        $data['path'] = $par->path.$data['pid'].',';
        $id = DB::table('type')->insertGetId($data);
        if($id>0){
            return redirect('admin/type')->with('msg','添加子类别成功');
        }
    }
}
